package com.deparse.mydialog.common;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/19.
 */
public class BaseActivity extends AppCompatActivity {
    private static List<Activity> activities = new ArrayList<Activity>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addActivity(this);

        Log.d("mylog", "add" + this.getClass().getSimpleName());
    }

    private static void addActivity(Activity activity) {
        activities.add(activity);
    }

    private static void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    public static void finishActivity(String... activityName) {

        if (activityName == null || activityName.length == 0) {
            for (Activity activity : activities) {
                if (!activity.isFinishing()) {
                    activity.finish();
                }
            }
        } else {

            for (Activity activity : activities) {
                String name = activity.getClass().getSimpleName();

                for (int i = 0; i < activityName.length; i++) {
                    if (activityName[i].equals(name)) {
                        activity.finish();
                        Log.d("mylog", "remove" + activityName);
                    }
                }

            }
        }

    }

    public void startActivity(Class<?> tClass, String... intentData) {
        Intent intent = new Intent();
        intent.setClass(this, tClass);
        intent.putExtra("IntentData", intentData);
        startActivity(intent);

    }

    public void startActivityWithTaskCleared(Class<?> cls, String... extras) {
        finishActivity();
        Intent intent = new Intent(this, cls);
        intent.putExtra("IntentData", extras);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        super.startActivity(intent);
    }

    public String[] getActivityStartExtra() {
        if (null == getIntent()) {
            return null;
        }
        return getIntent().getStringArrayExtra("IntentData");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeActivity(this);
        Log.d("mylog", "remove" + this.getClass().getSimpleName());
    }
}
